import { Button, Divider, Dropdown, message, Modal, Popconfirm, Space, Table, Upload, } from 'antd';
import React, { useEffect, useState } from 'react';
import Config from './config';
import axios from 'axios';
import {
  DOWNLOAD_TEMPLATE,
  GLOBAL_SELECTIONS,
  TALENT_DEL_TALENT,
  TALENT_LIST,
  TALENT_UPLOAD_FILES,
} from 'src/constants/api-constants';
import { useBoolean } from 'ahooks';
import { InboxOutlined } from '@ant-design/icons';
import FileSaver from 'file-saver';
import xlsx from 'node-xlsx';
import Detail from './detail';
import Insert from './insert';

const { Dragger } = Upload;

export default () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<any>([]);
  const [dataSource, setDataSource] = useState<TalentList.item[]>();
  const [page, setPage] = useState(1);
  const [name, setName] = useState('');
  const [talentType, setTalentType] = useState('');
  const [organization, setOrganization] = useState('');
  const [date, setDate] = useState('');
  const [applicationAreaOptions, setApplicationAreaOptions] = useState([]);
  const [organizationsTypeOptions, setOrganizationsTypeOptions] = useState([]);
  const [talentTypeOptions, setTalentTypeOptions] = useState([]);
  const [educationOptions, setEducationOptions] = useState([]);
  const [titleOptions, setTitleOptions] = useState([]);
  const [positionOptions, setPositionOptions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [count, setCount] = useState(0);
  const [isDetailShow, { setTrue: setDetailShow, setFalse: setDetailFalse }] =
    useBoolean(false);
  const [isInsertShow, { setTrue: setInsertShow, setFalse: setInsertFalse }] =
    useBoolean(false);
  const [record, setRecord] = useState<TalentList.item | { description: string }>();

  useEffect(() => {
    axios
      .get(GLOBAL_SELECTIONS)
      .then(r => {
        const { mainData } = r.data;

        const applicationAreaOptions = mainData.applicationArea.map(
          (item: any) => {
            return item.name;
          }
        );

        const organizationsTypeOptions = mainData.organizationType.map(
          (item: any) => {
            return item.name;
          }
        );

        const talentTypeOptions = mainData.talentType.map((item: any) => {
          return item.typeName;
        });

        const educationOptions = mainData.education.map((item: any) => {
          return item;
        });

        const titleOptions = mainData.titleType.map((item: any) => {
          return item.name;
        });

        const positionOptions = mainData.positionType.map((item: any) => {
          return item.name;
        });

        setApplicationAreaOptions(applicationAreaOptions);
        setOrganizationsTypeOptions(organizationsTypeOptions);
        setTalentTypeOptions(talentTypeOptions);
        setEducationOptions(educationOptions);
        setTitleOptions(titleOptions);
        setPositionOptions(positionOptions);
      })
      .catch(e => {
        console.log(e);
      });
  }, []);

  const getList = () => {
    setLoading(true);
    axios
      .post(TALENT_LIST, { page, name, talentType, organization, date })
      .then(r => {
        console.log(r);
        const { mainData } = r.data;
        setCount(mainData.count);

        const dataSource = mainData.rows.map((item: any, index: number) => {
          const today = new Date(item.updateTime);

          const time =
            today.getFullYear() +
            '-' +
            (today.getMonth() + 1) +
            '-' +
            today.getDate();
          console.log(item);

          return {
            ...item,
            key: item.uuid,
            titleName: item.title != null ? item.title.name : '',
            positionName: item.position != null ? item.position.name : '',
            applicationAreaName: item.application_area.name,
            talentTypeName: item.talent_classfication != null ? item.talent_classfication.typeName : '',
            updateTime: time,
          };
        });
        setLoading(false);
        setDataSource(dataSource);
      })
      .catch(e => {
        console.log(e);

        setLoading(false);
      });
    setLoading(false);
  };
  useEffect(getList, []);
  useEffect(getList, [page, name, talentType, organization, date]);

  let columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: 'break-all',
              width: 'auto',
              display: 'block',
              whiteSpace: 'pre-wrap',
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      render: (text: number) => {
        return (
          <span
            style={{
              wordBreak: 'break-all',
              width: 'auto',
              display: 'block',
              whiteSpace: 'pre-wrap',
            }}
          >
            {text === 1 ? '男' : '女'}
          </span>
        );
      },
    },
    {
      title: '人才类型',
      dataIndex: 'talentTypeName',
      key: 'talentTypeName',
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: 'break-all',
              width: 'auto',
              display: 'block',
              whiteSpace: 'pre-wrap',
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: '职称',
      dataIndex: 'titleName',
      key: 'titleName',
      render: (text: string, record: any) => {
        return (
          <span
            style={{
              wordBreak: 'break-all',
              width: 'auto',
              display: 'block',
              whiteSpace: 'pre-wrap',
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: '学历',
      dataIndex: 'education',
      key: 'education',
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: 'break-all',
              width: 'auto',
              display: 'block',
              whiteSpace: 'pre-wrap',
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: '行业领域',
      dataIndex: 'applicationAreaName',
      key: 'applicationAreaName',
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: 'break-all',
              width: 'auto',
              display: 'block',
              whiteSpace: 'pre-wrap',
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: '操作',
      render: (_text: any, record: any) => {
        if (window.localStorage.getItem('identity') === null) {
          return (<>
            <Space size={10}>
              <Button
                onClick={() => {
                  console.log(record);
                  const r = {
                    description: record.description
                  };
                  setRecord(r);
                  setDetailShow();
                }}
                style={{ padding: 0 }}
                type={'link'}
              >
                详情
              </Button>
            </Space>
          </>);
        } else {
          return (
            <>
              <Space size={10}>
                <Button
                  onClick={() => {
                    console.log(record);
                    let add = '';
                    let before: string[] = [];
                    if (record.address) {
                      const address = record.address?.split(';');
                      console.log(address);
                      if (address.length === 3) {
                        before = address;
                      } else {
                        before = address.slice(0, 3);
                        add = address.slice(3);
                      }
                    }
                    const r = {
                      ...record,
                      address: add,
                      addressBefore: before,
                      title: record.title.uuid,
                      position: record.position ? record.position.uuid : '',
                      applicationArea: record.application_area ? record.application_area.uuid : '',
                      talentType: record.talent_classfication ? record.talent_classfication.uuid : '',
                    };
                    setRecord(r);
                    setDetailShow();
                  }}
                  style={{ padding: 0 }}
                  type={'link'}
                >
                  详情
                </Button>
                <Popconfirm
                  title="确定删除?"
                  onConfirm={() => {
                    axios
                      .post(TALENT_DEL_TALENT, {
                        uuid: [record.uuid],
                      })
                      .then(r => {
                        const { mainData } = r.data;
                        if (mainData === 'success') {
                        } else {
                          message.error('该人才与专利库有关联，删除失败！');
                        }
                      })
                      .catch(_r => {
                        message.error('删除失败，请重试！');
                      })
                      .finally(() => {
                        setPage(1);
                        getList();
                      });
                  }}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button style={{ padding: 0 }} onClick={() => {
                  }} type={'link'}>
                    删除
                  </Button>
                </Popconfirm>
              </Space>
            </>
          );
        }
      },
    },
  ];

  // if (window.localStorage.getItem('identity') === null) {
  //   columns = columns.filter(column => {
  //     return column.title !== "操作";
  //   });
  // }

  const templateHead = [
    '姓名',
    '性别',
    '年龄',
    '工作单位',
    '单位性质',
    '职称',
    '职务',
    '行业领域',
    '人才类型',
    '学历',
    '电话',
    '邮箱',
    '居住地',
    '人才简历',
  ];
  const propsw: any = {
    name: 'file',
    action: TALENT_UPLOAD_FILES,
    headers: { Authorization: localStorage.getItem('Authorization') },
    data: { filler: localStorage.getItem('userName') },
    beforeUpload(file: File) {
      return new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = () => {
          if (reader.result && typeof reader.result !== 'string') {
            const buf = reader.result;
            const parse = xlsx.parse(buf, { type: 'buffer', cellStyles: true });
            const { data } = parse[0];
            console.log(data);

            const errData = data.slice(0, 3);
            let dataFilter = data.filter((item: any[], index: number) => {
              let flag = true;
              // 忽略批量上传文件的前三行
              let errItem: any = [];
              if (index !== 0 && index !== 1 && index !== 2) {
                errItem = [];
                for (let i = 0; i < templateHead.length; i++) {
                  // 忽略
                  if (i === 2 || i === 3 || i === 4 || i === 6 || i === 11) {
                    // 检查邮箱
                    if (i === 11) {
                      if (item[i] && !/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(item[i])) {
                        flag = false;
                        errItem.push(i);
                      } else {
                        continue;
                      }
                    } else {
                      continue;
                    }
                  } else if (!item[i]) {
                    // 检查每一列不为空
                    flag = false;
                    errItem.push(i);
                  }

                  // 检查职称
                  if (i === 5 && !titleOptions.some(v => v === item[i])) {
                    flag = false;
                    errItem.push(i);
                  }
                  // 检查职务
                  if (i === 6 && !positionOptions.some(v => v === item[i])) {
                    flag = false;
                    errItem.push(i);
                  }
                  // 检查学历
                  if (i === 9 && !educationOptions.some(v => v === item[i])) {
                    flag = false;
                    errItem.push(i);
                  }
                  // 检查行业领域
                  if (
                    i === 7 &&
                    !applicationAreaOptions.some(v => v === item[i])
                  ) {
                    flag = false;
                    errItem.push(i);
                  }
                  // 检查单位性质
                  if (
                    i === 4 &&
                    !organizationsTypeOptions.some(v => v === item[i])
                  ) {
                    flag = false;
                    errItem.push(i);
                  }
                  // 检查居住地
                  if (i === 12 && !/^.*?;.*?;.*?;.*?$/gi.test(item[i])) {
                    flag = false;
                    errItem.push(i);
                  }


                  // 检查手机号
                  if (i === 10 && !/^(((\(\d{3,4}\)|\d{3,4})?\d{7,8})|(1[3-9][0-9]{9}))$/.test(item[i])) {
                    flag = false;
                    errItem.push(i);
                  }
                  // 检查人才类型
                  if (i === 8 && !talentTypeOptions.some(v => v === item[i])) {
                    flag = false;
                    errItem.push(i);
                  }
                }
              }
              console.log(errItem);
              if (flag === false) {
                errData.push(
                  item.map((ceil, index) => {
                    if (errItem.some((v: any) => v === index)) {
                      return {
                        v: '(错误)' + ceil ?? '',
                        s: {
                          fill: {
                            fgColor: { rgb: 'FF0000' },
                          },
                        },
                      };
                    }
                    return ceil;
                  })
                );
              }
              return flag;
            });
            console.log('筛选数据', dataFilter);
            console.log('错误数据', errData);

            if (JSON.stringify(data[0]) !== JSON.stringify(templateHead)) {
              console.log(JSON.stringify(data[0]));
              console.log(JSON.stringify(templateHead));

              message.error(
                '上传文件中首行不正确请重试(请下载模板文件查看)',
                15
              );
            } else {
              const blob = new Blob(
                [xlsx.build([{ name: 'template', data: dataFilter }])],
                {
                  type: 'application/octet-stream',
                }
              );
              if (dataFilter.length !== data.length) {
                message.info('已将筛选出正确数据并上传', 15);
                message.info('已返回错误数据文件', 15);
                const blob1 = new Blob(
                  [xlsx.build([{ name: 'errData', data: errData }])],
                  {
                    type: 'application/octet-stream',
                  }
                );
                FileSaver.saveAs(blob1, 'errData.xlsx');
              }
              resolve(blob);
            }
          } else {
            message.error('文件读取失败请检查格式');
          }
        };
      });
    },
    onChange(info: {
      file: {
        response: { msg: string };
        status: string;
        name: string;
      };
      fileList: any;
    }) {
      if (info.file.status === 'done') {
        setPage(1);
        getList();
        message.success(`${info.file.name} 上传成功.`);
        message.success(info.file.response.msg);
      } else if (info.file.status === 'error') {
        setPage(1);
        getList();
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };
  const menu = (
    <div
      style={{
        background: 'rgb(251,251,251)',
        padding: '12px',
        boxShadow: '3px 3px 3px 3px rgb(193,193,195)',

        borderRadius: '3px',
      }}
    >
      <Button
        onClick={() => {
          axios
            .post(DOWNLOAD_TEMPLATE, {
              filename: 'talentTemplate.xlsx',
              dir: 'talent',
            })
            .then(r => {
              const { file, filename } = r.data.mainData;
              console.log(file);
              let blob = new Blob([xlsx.build(file)], {
                type: 'application/octet-stream',
              });
              FileSaver.saveAs(blob, filename);
            })
            .catch(e => {
              console.log(e);
            });
        }}
        style={{
          overflow: 'hidden',
          whiteSpace: 'normal',
          wordBreak: 'break-all',
          fontSize: '0.9rem',
          padding: '0',
          width: '10vw',
          height: 'auto',
          marginBottom: '2vh',
        }}
      >
        下载导入模板
      </Button>
      <Dragger accept={'.xlsx'} {...propsw} style={{ padding: '0 1vw' }}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">请拖拽.XLSX文件至此或使用点击上传</p>
        <p className="ant-upload-hint">
          支持单次或批量上传。 严禁上传公司资料或其他公司文件
        </p>
      </Dragger>
    </div>
  );

  return (
    <>
      <Config
        setDate={setDate}
        setName={setName}
        setOrganization={setOrganization}
        setPage={setPage}
        setTalentType={setTalentType}
      />

      <Divider />
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <h2 style={{ fontWeight: 'bold', display: 'inline-block' }}>
          详细信息
        </h2>
        {
          window.localStorage.getItem('identity') === null ?
            null
            :
            <Space>
              <Dropdown
                trigger={['click']}
                placement="bottomRight"
                arrow
                overlay={menu}
              >
                <Button type="primary">批量导入</Button>
              </Dropdown>
              <Button type="primary" onClick={setInsertShow}>
                添加人才信息
              </Button>
            </Space>
        }
      </div>

      <Table
        pagination={{
          current: page,
          showSizeChanger: false,
          pageSize: 10,
          total: count,
          onChange: (page, _pageSize) => {
            setLoading(true);
            setPage(page);
            setLoading(false);
          },
        }}
        footer={() => {
          return (
            <>
              {
                window.localStorage.getItem('identity') === null ?
                  null
                  :
                  <Space>
                    <Button
                      type="default"
                      onClick={() => {
                        if (dataSource) {
                          const data: string[][] = [
                            [
                              '姓名',
                              '性别',
                              '电话',
                              '邮箱',
                              '年龄',
                              '职称',
                              '职务',
                              '学历',
                              '行业领域',
                              '工作单位',
                              '单位性质',
                              '居住地',
                              '人才类型',
                              '人才简历',
                            ],
                          ];
                          selectedRowKeys.forEach((v: string) => {
                            const item = dataSource.find((value: TalentList.item) => {
                              return value.uuid === v;
                            });
                            if (item) {
                              console.log(item);
                              data.push([
                                item.name,
                                item.sex === '0' ? '女' : '男',
                                item.tel,
                                item.email,
                                item.age,
                                item.titleName,
                                item.positionName,
                                item.education,
                                item.applicationAreaName,
                                item.unit,
                                item.organization_type.name,
                                item.address,
                                item.talentTypeName,
                                item.description,
                              ]);
                            }
                          });
                          if (data.length !== 1) {
                            const blob = new Blob(
                              [xlsx.build([{ name: 'output', data }])],
                              {
                                type: 'application/octet-stream',
                              }
                            );
                            FileSaver.saveAs(blob, '人才信息导出表.xlsx');
                          }
                        }
                      }}
                    >
                      批量导出
                    </Button>
                    <Popconfirm
                      title="确定删除?"
                      onConfirm={() => {
                        axios
                          .post(TALENT_DEL_TALENT, {
                            uuid: selectedRowKeys,
                          })
                          .then(r => {
                            const { mainData } = r.data;
                            if (mainData === 'success') {
                            } else {
                              message.error('该人才与专利库有关联，删除失败！');
                            }
                          })
                          .catch(_r => {
                            message.error('删除失败，请重试');
                          })
                          .finally(() => {
                            setPage(1);
                            getList();
                          });
                      }}
                      okText="确定"
                      cancelText="取消"
                    >
                      <Button type="default">批量删除</Button>
                    </Popconfirm>
                  </Space>
              }
            </>
          );
        }}
        loading={loading}
        size={'middle'}
        rowSelection={{
          selectedRowKeys,
          onChange: value => {
            console.log(value);
            setSelectedRowKeys(value);
          },
        }}
        columns={columns}
        dataSource={dataSource}
      />
      <Modal
        title="人才详细信息"
        visible={isDetailShow}
        onCancel={setDetailFalse}
        width={'80vw'}
        centered={true}
        footer={null}
        destroyOnClose
      >
        <Detail
          setDetailFalse={setDetailFalse}
          record={record}
          getList={getList}
          setPage={setPage}
        />
      </Modal>

      <Modal
        title="添加人才信息"
        visible={isInsertShow}
        onCancel={setInsertFalse}
        width={'80vw'}
        centered={true}
        footer={null}
        destroyOnClose
      >
        <Insert
          setInsertFalse={setInsertFalse}
          getList={getList}
          setPage={setPage}
        />
      </Modal>
    </>
  );
};
